package hk.linkcredit.awardservice.rocketmq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import hk.linkcredit.common.rocketmq.util.RocketMqUtils;
import hk.linkcredit.awardservice.award.domain.entity.AwardRecord;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author cyh
 * @date 2022/7/4 12:03 下午
 */
@Component
public class AwardProducer {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmq.topics.walletAccountTopic}")
    private String awardDistributionTopic;


    public TransactionSendResult sendAwardMessageInTransaction(List<AwardRecord> recordList) {

        //消息内容
        JSONArray jsonValues = new JSONArray();
        recordList.forEach(e -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("reference", e.getSerialNo());
            jsonObject.put("custNo", e.getCustNo());
            jsonObject.put("amount", e.getAwardAmount());
            jsonObject.put("fundsType", "1");
            jsonValues.add(jsonObject);
        });

        String msg = jsonValues.toString();
        //同批流水号
        String bizId = recordList.get(0).getSerialNo();
        return RocketMqUtils.sendMessageInTransaction(rocketMQTemplate, awardDistributionTopic, msg, bizId, bizId, "awardActivityTransactionHandler", recordList);
    }

}
